﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace workWithFiles
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Stream myStream;

        private void button1_Click(object sender, EventArgs e)
        {
            Stream myStream = null;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((this.myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (this.myStream)
                        {
                            // create reader & open file
                            TextReader tr = new StreamReader(this.myStream);

                            // read a line of text
                            textBox1.Text = tr.ReadToEnd();

                            // close the stream
                            tr.Close();
                            button2.Enabled = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.myStream != null)
            {
                try
                {
                    // create a writer and open the file
                    TextWriter tw = new StreamWriter(this.myStream);

                    // write a line of text to the file
                    tw.Write(textBox1.Text);

                    // close the stream
                    tw.Close();
                    button2.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (this.myStream != null)
            {
                button2.Enabled = true;
            }
        }
    }
}
